<!--
@description ：创建小程序
-->

<template>
  <div class="app-container">
    <div class="title-header" style="display: flex">
      <div class="text">{{ $route.query.flag == '1' ? '创建小程序' : '编辑小程序' }}</div>
      <div class="button">
        <el-button :loading="sureLoading" type="primary" @click="submitButton('form')">确定</el-button>
        <el-button @click="$router.go(-1)">取消</el-button>
      </div>
    </div>
    <div class="create-content">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="小程序名称" prop="name">
          <el-input v-model="form.name" clearable placeholder="请输入小程序名称" style="width: 600px"></el-input>
        </el-form-item>
        <el-form-item label="小程序ID" prop="programId">
          <el-input v-model="form.programId" clearable placeholder="请输入小程序ID" style="width: 600px"></el-input>
        </el-form-item>
        <el-form-item label="小程序图片" required>
          <div class="upload">
            <el-upload
              :before-upload="beforeUploadImg"
              :show-file-list="false"
              action
              list-type="picture-card"
            >
              <i class="el-icon-plus"></i>
              <div slot="tip" class="el-upload__tip" style="color: #CCCCCC">
                上传图片大小不超过10MB
              </div>
            </el-upload>
            <div v-for="(item, index) in imgs" :key="index" class="img" style="margin-left: 6px">
              <img v-if="item" :src="item" width="100%"/>
              <div class="imgPre">
                <i class="el-icon-zoom-in" @click="dialogVisible = true, dialogImageUrl = item"></i>
                <i class="el-icon-delete" @click="handleRemove(index)"></i>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog :close-on-click-modal="false" :visible.sync="dialogVisible" append-to-body title="图片预览"
               width="600px">
      <img :src="dialogImageUrl" alt="" width="100%">
    </el-dialog>
  </div>
</template>
<script>
import {uploadImgFile} from "@/api/communityOperating/fileManage";
import {queryProgramDetail, saveOrUpdateProgram} from "@/api/smallProgram";

export default {
  name: "createSmallProgram", //页面名称，必填
  props: {},
  components: {},
  data() {
    return {
      form: {
        name: '',
        programId: '',
      },
      rules: {
        name: [{required: true, message: '请输入小程序名称', trigger: 'blur'},
          { required: true, max: 20, message: '小程序名称在20字内，请核对后再输入', trigger: 'blur'}],
        programId: [{required: true, message: '请输入有效的小程序ID', trigger: 'blur'}]
      },
      imgs: [],
      sureLoading: false,
      dialogVisible: false,
      dialogImageUrl: '',
    }
  },
  watch: {},
  methods: {
    // 确认
    submitButton() {
      if (this.imgs.length == 0) return this.$message.error('请上传小程序图片')
      let params = {
        ...this.form,
        smallId: this.$route.query.id || '',
        pictureUrl: this.imgs[0]
      }
      this.$refs.form.validate((valid) => {
        if(valid){
          this.sureLoading = true
          saveOrUpdateProgram(params).then(res => {
            if (res.code == 200) {
              this.$message.success(this.$route.query.flag == '1' ? '创建小程序成功' : '编辑小程序成功')
              this.$router.go(-1)
            }
            this.sureLoading = false
          }).catch(() => {
            this.sureLoading = false
          })
        }
      })
    },
    // 图片上传
    async beforeUploadImg(img) {
      console.log(img)
      const type = ['image/png', 'image/jpg', 'image/gif', 'image/jpeg']
      const isJPG = type.includes(img.type)
      const isLt10M = img.size / 1024 / 1024 < 10

      if (!isJPG) {
        this.$message.error('上传图片支持jpg、png、gif格式!')
      } else if (!isLt10M) {
        this.$message.error('您上传的文件超过10MB!')
      } else {
        console.log(img, '====img')
        const formData = new FormData()
        formData.append('file', img)
        const {data} = await uploadImgFile(formData)
        console.log(data, 'data',)
        this.imgs = [window.globalConfig.IMAGE_API + data.url]
        console.log(this.imgs[0])
        this.form.photoName = data.fileName
        this.form.photoUrl = data.url
      }
    },
    // 图片删除
    handleRemove(index) {
      this.$confirm('是否确认删除所选图片？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.imgs.splice(index, 1)
      }).catch()
    },
  },
  mounted() {
      if(this.$route.query.id){
        queryProgramDetail({smallId: String(this.$route.query.id)}).then(res => {
          if(res.code == 200){
            this.form = {
              ...res.data,
              photoUrl: res.data.pictureUrl || ''
            }
            this.imgs = [res.data.pictureUrl || '']
          }
        })
      }
  },
  created() {
  },
}

</script>

<style lang="scss" scoped>

.app-container {
  height: 100%;
}


.app-container {
  height: 100%;
  padding: 0;

  .title-header {
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
    background-color: white;
    height: 60px;
    padding-left: 20px;
    padding-right: 20px;
    border-radius: 6px;

    .text {
      font-size: 20px;
    }
  }

  .create-content {
    background-color: white;
    border-radius: 6px;
    padding: 10px 0;
    min-height: calc(100vh - 192px);
  }
}


.img {
  position: relative;
  width: 148px;
  height: 148px;
  margin-right: 10px;

  img {
    height: 100%;
  }

  .imgPre {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    background: rgba(238, 238, 238, 0.4);
    display: flex;
    justify-content: space-around;
    align-items: center;
    opacity: 0;

    &:hover {
      opacity: 1;
    }

    i {
      font-size: 22px;
      color: #fff;
    }
  }
}

.upload {
  display: flex;
}

.switch-input {
  padding: 4px 0 0 10px !important;

  ::v-deep.el-form-item__content {
    line-height: 30px;
    display: flex;
    align-items: center;
  }
}
</style>
